package com.itheima.manage.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.itheima.manage.config.MyCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.concurrent.TimeUnit;

/**
 * @author yaohu
 * @date 2021/12/8
 * @Version 1.0
 * @describe 对响应体增强
 */
@ControllerAdvice
public class CacheResponseBody implements ResponseBodyAdvice {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 如果这个方法的返回值是true  就会走下面的beforeBodyWrite这个方法
     * 如果这个方法的返回值是false 就不会走下面的beforeBodyWrite这个方法
     *
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 必须是GET请求，必须有MyCache注解
        return returnType.hasMethodAnnotation(GetMapping.class) && returnType.hasMethodAnnotation(MyCache.class);
    }

    /**
     * 增强响应体
     *
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (ObjectUtil.isNull(body)) {
            return null;
        }

        // 把body存储到redis中
        String redisValue = null;
        // 如果是String类型 直接存
        if (body instanceof String) {
            redisValue = (String) body;
        } else {
            // 如果不是String类型 转为JSON存
            redisValue = JSONUtil.toJsonStr(body);
        }

        // 获取redis的key
        // Redis的Key
        String cacheKey = CacheInterceptor.getCacheKey(((ServletServerHttpRequest) request).getServletRequest());

        // 拿到目标方法上的注解 然后获取它的缓存时间
        MyCache myCache = returnType.getMethodAnnotation(MyCache.class);
        // 把缓存数据存储到redis中
        redisTemplate.opsForValue().set(cacheKey, redisValue, myCache.cacheTime(), TimeUnit.SECONDS);

        System.out.println("已经把响应体中的数据存储到redis中...");

        return body;
    }
}
